﻿using System;
using RBOSS.Business.CustomerModule;
using RBOSS.Business.LoginModule;
using RBOSS.Utilities;
using RBOSS.WebUI.Models;


namespace RBOSS.WebUI
{
    public partial class Login : MasterSite
    {
        private LoginSubSystem _loginSubSystem;
        protected void Page_Load(object sender, EventArgs e)
        {
            _loginSubSystem = new LoginSubSystem();
            butProcceedAsGuest.Click += ProcceedAsGuestClick;
        }

        

        protected void BtnLoginClick(object sender, EventArgs e)
        {

            var userName = txtUserEmail.Text;
            var password = RBOSSecurity.Encrypt(txtPassword.Text);
            var source = Request.QueryString["Source"];

            if (_loginSubSystem.ValidateLogin(userName, password))
            {
                var role = _loginSubSystem.GetRole(userName);
                Session["email"] = userName;
                Session["name"] = string.Format("{0} {1}","Welcome", _loginSubSystem.GetName(userName)); ;
                Session["role"] = role;
                if (role == "Customer")
                {
                    InitialCustomerInformation(userName);
                    if (source == null)
                    {
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        Response.Redirect(source + ".aspx");
                    }
                }
                else if (role == "Admin")
                    Response.Redirect("Adminhome.aspx");
                else if (role == "Vendor")
                    Response.Redirect("VendorProductsUI.aspx");
                else
                    Response.Redirect("Default.aspx");
            }
            else
            {
                FailureText.Text = "Invalid username or password.";
                ErrorMessage.Visible = true;
            }

        }

        private void InitialCustomerInformation(string email)
        {
            ICustomerSubSystem customerSubSystem = new CustomerSubSystem();
            customerSubSystem.RegisterCustomerInSession(email);
            
        }

        private void ProcceedAsGuestClick(object sender, EventArgs e)
        {
            ICustomerSubSystem customerSubSystem = new CustomerSubSystem();
            customerSubSystem.RegisterCustomerInSession(string.Empty);
            var source = Request.QueryString["Source"];
            if (source == null)
            {
                Response.Redirect("Default.aspx");
            }
            else
            {
                Response.Redirect(source + ".aspx");
            }
        }

        protected void BtnForgetPasswordClick(object sender, EventArgs e)
        {

        }
    }
}